<?php

/*
	PIE Content Management System
	John Girata
	Licensed under the GNU General Public License version 3
*/

defined('PIESECVAR') or die('Restricted Access');

class com_update_page
{
	function __construct()
	{
		if(!isset($_GET['page']))
			$this->get_page_id();
		else if(isset($_POST['submit']))
			$this->check_and_store();
		else
			$this->load_form();
	}
	
	function get_page_id($error = '')
	{
		global $controller, $db;
		
		$form = file_get_contents(TMPL_DIR . 'com.update_page/get_page.tmpl');
		$select = '<select name="page">';
		
		$db->query("SELECT `id`,`title` FROM `#__pages` WHERE `deleted`='0'");
		$return = $db->get_array();
		
		foreach($return as $item)
			$select .= '<option value="' . $item['id'] . '">' . $item['title'] . '</option>';
		
		$select .= '</select>';
		
		$patterns = Array(
			'/<%%ERROR%%>/',
			'/<%%PAGES%%>/'
		);
		
		$replacements = Array(
			$error,
			$select
		);
		
		$form = preg_replace($patterns, $replacements, $form);
		
		$controller->add_content($form);
	}
	
	function load_form($error = '')
	{
		global $controller, $db;
		
		$form = file_get_contents(TMPL_DIR . 'com.update_page/com.update_page.tmpl');
		
		$id = $db->escape($_GET['page']);
		$db->query("SELECT * FROM `#__pages` WHERE `id`='$id'");
		$page_info = $db->get_array();
		$page_info = $page_info[0];
		
		$db->query("SELECT `id`,`name` FROM `#__groups`");
		$group_info = $db->get_array();
		
		$checkboxes = '';
		$groups = Array();
		
		$groups = explode(',', $page_info['groups']);
		
		foreach($group_info as $item)
		{
			$checkboxes .= '<input type="checkbox" name="group-' . $item['id'] . '" ';
			
			if(in_array($item['id'], $groups))
				$checkboxes .= 'checked="yes" ';
			
			$checkboxes .= '/> ' . $item['name'] . '<br />';
		}
		
		$hide_to_guests = ($page_info['hide_to_guests'] == 0) ? 'selected="yes"' : '';
		
		$patterns = Array(
			'/<%%ERROR%%>/',
			'/<%%TITLE%%>/',
			'/<%%CONTENT%%>/',
			'/<%%HIDE_TO_GUESTS%%>/',
			'/<%%GROUPS%%>/'
		);
		
		$replacements = Array(
			$error,
			$page_info['title'],
			$page_info['content'],
			$hide_to_guests,
			$checkboxes
		);
		
		$form = preg_replace($patterns, $replacements, $form);
		
		$controller->add_content($form);
	}
	
	function check_and_store()
	{
	
	}
}

$com_update_page = new com_update_page();

?>